//
//  OAContactPersonListViewController.m
//  ERP
//
//  Created by goldeney on 15/1/21.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OAContactPersonListViewController.h"
#import "OAContactPersonDetailViewController.h"

#import "MJRefresh.h"
#import "OAContactPersonListViewCell.h"
#import "UITableView+Custom.h"
#import "ServiceConnect.h"
#import "AddressBookEntity.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

@interface OAContactPersonListViewController ()

@property (nonatomic, strong) NSMutableArray *addressBookArray;
@property (nonatomic, strong) NSDictionary *parameterDict;

@end

@implementation OAContactPersonListViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"集团联系人"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.addressBookArray = [NSMutableArray array];
    
    self.tableView.tableFooterView= [[UIView alloc] init];
    [self setupRefresh];
}

//获取上一个页面传递的参数
- (void)getPassingParameter:(id)object
{
    self.parameterDict = object;
    [self setTitle:[self.parameterDict objectFormatStringForKey:@"orgName"]];
}

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:[self.parameterDict objectFormatForKey:@"id"] forKey:@"orgId"];
    [model setValue:state forKey:@"between"];
    [model setValue:end forKey:@"and"];
    [model setValue:nil forKey:@"searchVal"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_Mail_list" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self stopRefresh];//关闭下拉菜单
        //添加数据，刷新页面
        if(result.resultArray && result.resultArray.count>0){
            if(isReresh) [self.addressBookArray removeAllObjects];
            [self.addressBookArray addObjectsFromArray:result.resultArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无联系人" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"==failed===%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"==abnormal===%@",error);
        if(isReresh)[self errorInfoViewText:@"网络异常"];
    }];
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:1];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

- (void)footerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:self.addressBookArray.count + 1];
    NSNumber *endNumber = [NSNumber numberWithInteger:self.addressBookArray.count + 10];
    [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.addressBookArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierOne = @"OAContactPersonListViewCell";
    OAContactPersonListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
    if (!cell)
        cell = [[OAContactPersonListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
    
    NSDictionary *dictionary = [self.addressBookArray objectAtIndex:indexPath.row];
    cell.titleLable.text = [dictionary objectFormatStringForKey:@"userName"];
    cell.postLable.text = [dictionary objectFormatStringForKey:@"deptName"];
    
    NSString *phone = [dictionary objectFormatStringForKey:@"mobileNumber"];
    if (phone && ![phone isEqualToString:@""]) cell.phoneLable.text = phone;
    else cell.phoneLable.text = @"暂无";
    
    cell.callButton.tag = indexPath.row;
    [cell.callButton addTarget:self action:@selector(callSelector:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 66;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dictionary = [self.addressBookArray objectAtIndex:indexPath.row];
    
    OAContactPersonDetailViewController *viewController = [[OAContactPersonDetailViewController alloc] initWithValue:dictionary];
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark
#pragma mark - Button Event

- (void)callSelector:(UIButton*)button
{
    //获取电话号码
    NSInteger numberType = button.tag;
    NSDictionary *dictionary = [self.addressBookArray objectAtIndex:numberType];
    
    NSMutableString *phoneNumber = [[NSMutableString alloc] init];
    [phoneNumber appendString:@"tel://"];
    
    NSString *mobliePhone = [dictionary objectForKey:@"mobileNumber"];
    if (mobliePhone && ![mobliePhone isEqualToString:@""]){//拨打移动号码
        [phoneNumber appendString:mobliePhone];
        
    }else {
        //未找到手机号码
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"未找到联系人电话号码" delegate:self
                                            cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        return;
    }
    
    //保存拨打联系人
    [self saveUserCallPhoneNumber:dictionary];
    
    //拨打电话(合法拨打电话方式)
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:phoneNumber];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    [self.view addSubview:callWebview];
}


#pragma mark
#pragma mark - 保存拨打联系人

- (void)saveUserCallPhoneNumber:(NSDictionary*)temp
{
    //保存拨打联系人
    NSString *phoneUserID = [[temp objectFormatStringForKey:@"userId"] MD5];
    NSArray *students = [AddressBookEntity MR_findByAttribute:@"identifyID" withValue:phoneUserID];
    if (students && students.count<=0){
        //插入联系人数据
        UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
        AddressBookEntity *person = [AddressBookEntity MR_createEntity];
        person.identifyID = phoneUserID;
        person.createUserId = [userInfo.Id MD5];
        person.userName = [temp objectFormatStringForKey:@"userName" defaults:@"未录入"];
        person.orgName = [temp objectFormatStringForKey:@"orgName" defaults:@"未录入"];
        person.deptName = [temp objectFormatStringForKey:@"deptName" defaults:@"未录入"];
        person.postName = [temp objectFormatStringForKey:@"postName" defaults:@"未录入"];
        person.officePhone = [temp objectFormatStringForKey:@"officePhone" defaults:@"未录入"];
        person.companyEmail = [temp objectFormatStringForKey:@"companyEmail" defaults:@"未录入"];
        person.homePhone = [temp objectFormatStringForKey:@"homePhone" defaults:@"未录入"];
        person.mobileNumber = [temp objectFormatStringForKey:@"mobileNumber" defaults:@"未录入"];
        person.callTime = [NSDate date];
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        
    } else {
        //更新联系人数据
        AddressBookEntity *entity = [students firstObject];
        entity.userName = [temp objectFormatStringForKey:@"userName" defaults:@"未录入"];
        entity.orgName = [temp objectFormatStringForKey:@"orgName" defaults:@"未录入"];
        entity.deptName = [temp objectFormatStringForKey:@"deptName" defaults:@"未录入"];
        entity.postName = [temp objectFormatStringForKey:@"postName" defaults:@"未录入"];
        entity.officePhone = [temp objectFormatStringForKey:@"officePhone" defaults:@"未录入"];
        entity.companyEmail = [temp objectFormatStringForKey:@"companyEmail" defaults:@"未录入"];
        entity.homePhone = [temp objectFormatStringForKey:@"homePhone" defaults:@"未录入"];
        entity.mobileNumber = [temp objectFormatStringForKey:@"mobileNumber" defaults:@"未录入"];
        entity.callTime = [NSDate date];
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
    }
}

@end

